package com.itheima.reggie.controlle;

import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 地址管理
 */
@RestController
@RequestMapping("addressBook")
public class AddressBookController {
    @Autowired
    AddressBookService addressBookService;

    /**
     * 根据线程id查询地址
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> listAction(){

        List<AddressBook> addressBookList = addressBookService.lambdaQuery()
                .eq(AddressBook::getUserId, BaseContext.get())
                .orderByDesc(AddressBook::getUpdateTime).list();
        return R.success(addressBookList);
    }

    /**
     * 设置默认地址
     */
    @PutMapping("/default")
    public R<AddressBook> defaultAction(@RequestBody AddressBook addressBook){
        //update addressBook set is_default=0 where id =?
        addressBookService.update()
                .eq("user_id",BaseContext.get()) //先判断哪个用户的地址
                .set("is_default",0) //设置等于0
                .update();
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    /**
     * 根据id回显地址信息
     */
    @GetMapping("/{id}")
    public R<AddressBook> findById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.lambdaQuery()
                .eq(AddressBook::getUserId, BaseContext.get())
                .eq(AddressBook::getId, id).one();
        return R.success(addressBook);
    }

    /**
     * 修改地址信息
     */
    @PutMapping
    private R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.saveOrUpdate(addressBook);
        return R.success("修改成功");
    }

    /**
     * 添加地址
     */
    @PostMapping
    private R<String> add(@RequestBody AddressBook addressBook){
        //设置用户id
        addressBook.setUserId(BaseContext.get());
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    /**
     * 回显默认地址
     * @return
     */
    @GetMapping("default")
    private R<AddressBook> findAddress(){
        AddressBook addressBook = addressBookService.lambdaQuery()
                .eq(AddressBook::getUserId, BaseContext.get())
                .eq(AddressBook::getIsDefault,1)
                .one();
        return R.success(addressBook);
    }
}
